import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Query {
    public void query() throws SQLException {
        //1.创建数据源 DataSource
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/ebook?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");
        //2.建立连接
        Connection connection = dataSource.getConnection();
        //3.构造 sql 语句
        String sql = "select category.name as category_name, student.name as student_name, book.name as book_name, borrow_info.start_time, borrow_info.end_time from category join book on category.id = book.category_id join borrow_info on borrow_info.book_id = book.id join student on borrow_info.student_id = student.id where category.name = '计算机'";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //4.执行 sql 语句
        ResultSet resultSet = preparedStatement.executeQuery();
        //5.遍历查询结果
        while(resultSet.next()){
            String category_name = resultSet.getString("category_name");
            String student_name = resultSet.getString("student_name");
            String book_name = resultSet.getString("book_name");
            String start_time = resultSet.getString("start_time");
            String end_time = resultSet.getString("end_time");

            System.out.println("categoryName: " + category_name + ", studentName: " + student_name + ", bookName: " + book_name + ", startTime: " + start_time + ", endTime: " + end_time);
        }
        //6.释放资源
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}
